import 'dart:async';
import 'dart:io';
import 'dart:typed_data';
import 'dart:ui';
import 'dart:ui' as ui;
import 'package:carousel_slider/carousel_slider.dart' as carousel;
import 'package:carousel_slider/carousel_slider.dart';
import 'package:image_picker/image_picker.dart';
import 'package:path_provider/path_provider.dart';

import 'package:custom_widgets/screen_util.dart';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter/rendering.dart';
import 'package:fluwx/fluwx.dart';
// import 'package:image_gallery_saver/image_gallery_saver.dart';
import 'package:mi_mang_flutter/config/configs.dart';
import 'package:mi_mang_flutter/generated/icon/Iconfont.dart';
import 'package:mi_mang_flutter/model/daily_word_model.dart';
import 'package:mi_mang_flutter/res/dimens.dart';
import 'package:mi_mang_flutter/res/styles.dart';
import 'package:mi_mang_flutter/utils/formDate.dart';
import 'package:mi_mang_flutter/utils/image_utils.dart';
import 'package:mi_mang_flutter/utils/locale_util.dart';
import 'package:mi_mang_flutter/utils/shared_preferences.dart';
import 'package:mi_mang_flutter/utils/toast_util.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:share_plus/share_plus.dart';

/// 每日一图
class DailySharePage extends StatefulWidget {
  // 当前选中的每日一句
  final DailyWordModel? model;

  DailySharePage({Key? key, this.model}) : super(key: key);

  @override
  _DailySharePageState createState() => _DailySharePageState();
}

class _DailySharePageState extends State<DailySharePage>
    with SingleTickerProviderStateMixin {
  GlobalKey<_DailySharePageState> globalKey1 = GlobalKey();
  GlobalKey<_DailySharePageState> globalKey2 = GlobalKey();
  GlobalKey<_DailySharePageState> globalKey3 = GlobalKey();

  // 当前选中分享内容的索引
  int selectIndex = 0;

  /// 底部分享栏位置动画
  late Animation<double> animation;
  late AnimationController controller;

  /// 分享内容渐变动画
  late CurvedAnimation _curvedAnimation;
  late Tween _opacityTween;
  Curve _curve = Curves.easeIn;

  // 当前选中的每日一句
  DailyWordModel? _model;

  // 底部分享栏的高度
  double _bottomShareHeight = 0;

  double _textScaleFactor = 0.8;

  final carousel.CarouselSliderController _carouselController =
      carousel.CarouselSliderController();

  @override
  void initState() {
    super.initState();
    _initData();
    _initAnimation();
    _listenWeChat();
  }

  _initData() {
    // 初始化底部分享栏高度
    _bottomShareHeight = Dimens.widthDp(280.0);

    // 避免异常,如果没有传入分享对象,使用本地缓存的启动图
    if (widget.model != null) {
      _model = widget.model;
    } else {
      var modelMap = SpUtil.getObject(SPKeys.HOME_DAILY_KEY);
      if (modelMap != null) {
        _model = DailyWordModel.fromJson(modelMap);
      }
    }
  }

  _initAnimation() {
    controller =
        AnimationController(duration: kThemeAnimationDuration, vsync: this);
    animation = Tween(begin: -_bottomShareHeight, end: Dimens.gapDp10)
        .chain(CurveTween(curve: _curve))
        .animate(controller)
      ..addListener(() {
        // 执行动画时刷新页面状态
        setState(() {});
      })
      ..addStatusListener((state) {
        // 动画逆序执行完毕后,关闭当前页
        if (state == AnimationStatus.dismissed) {
          Navigator.maybePop(context);
        }
      });

    _curvedAnimation = CurvedAnimation(parent: controller, curve: _curve);
    _opacityTween = Tween<double>(begin: 0.0, end: 1.0);

    // 启动动画
    controller.forward();
  }

  _listenWeChat() {
    // weChatResponseEventHandler.listen((res) {
    //   if (res is WeChatShareResponse) {
    //     Toast.showSuccess("分享成功");
    //   }
    // });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Stack(
        children: <Widget>[
          ConstrainedBox(
            // 限制条件，可扩展的
            constraints: BoxConstraints.expand(),
            child: loadNetworkImage(
              _model?.imageUrl ?? '',
              fit: BoxFit.cover,
            ),
          ),
          Positioned.fill(
            child: BackdropFilter(
              filter: ImageFilter.blur(
                sigmaX: 50.0,
                sigmaY: 50.0,
              ),
              child: InkWell(
                child: Container(color: Colors.black38),
                onTap: () {
                  controller.reverse();
                },
              ),
            ),
          ),
          GestureDetector(
            onTap: controller.reverse,
            child: FadeTransition(
              opacity:
                  _opacityTween.animate(_curvedAnimation) as Animation<double>,
              child: CarouselSlider.builder(
                options: CarouselOptions(
                  height: double.infinity,
                  viewportFraction: 1.0,
                  enlargeCenterPage: false,
                  scrollPhysics: ClampingScrollPhysics(),
                  initialPage: selectIndex,
                  onPageChanged: (index, reason) {
                    selectIndex = index;
                    if (mounted) setState(() {});
                  },
                ),
                itemCount: 3,
                itemBuilder: _swiperItem,
              ),
            ),
          ),
          Positioned(
            left: Dimens.gapDp10,
            bottom: _bottomShareHeight + Dimens.gapDp50,
            right: Dimens.gapDp10,
            child: FadeTransition(
              opacity:
                  _opacityTween.animate(_curvedAnimation) as Animation<double>,
              child: Row(
                mainAxisAlignment: MainAxisAlignment.center,
                children: Iterable<int>.generate(3).map((int pageIndex) {
                  return GestureDetector(
                    onTap: () => _carouselController.animateToPage(pageIndex),
                    child: Container(
                      width: 12.0,
                      height: 12.0,
                      margin:
                          EdgeInsets.symmetric(vertical: 8.0, horizontal: 4.0),
                      decoration: BoxDecoration(
                          shape: BoxShape.circle,
                          color: Colors.white
                              .withAlpha(selectIndex == pageIndex ? 230 : 102)),
                    ),
                  );
                }).toList(),
              ),
            ),
          ),
          _buildBottom(),
        ],
      ),
      backgroundColor: Theme.of(context).colorScheme.surface,
    );
  }

  Widget _swiperItem(BuildContext context, int index, int realIndex) {
    return GestureDetector(
      onTap: () {},
      child: _buildShareImage(index),
    );
  }

  Widget _buildShareImage(int index) {
    switch (index) {
      case 0:
        return Container(
          alignment: Alignment(0.0, -0.7),
          margin: EdgeInsets.only(
            top: ScreenUtil.bottomBarHeight! * 3,
            bottom: ScreenUtil.bottomBarHeight! * 1,
          ),
          child: FractionallySizedBox(
            widthFactor: 0.6,
            heightFactor: 0.6,
            child: _shareImage1(),
          ),
        );
      case 1:
        return Container(
          alignment: Alignment(0.0, -0.7),
          margin: EdgeInsets.only(
            top: ScreenUtil.bottomBarHeight! * 3,
            bottom: ScreenUtil.bottomBarHeight! * 1,
          ),
          child: FractionallySizedBox(
            widthFactor: 0.6,
            heightFactor: 0.6,
            child: _shareImage2(),
          ),
        );
      case 2:
        return Container(
          alignment: Alignment(0.0, -0.4),
          margin: EdgeInsets.only(
            top: ScreenUtil.bottomBarHeight! * 3,
          ),
          child: FractionallySizedBox(
            widthFactor: 0.6,
            child: AspectRatio(
              aspectRatio: 1.0,
              child: _shareImage3(),
            ),
          ),
        );
      default:
        return SizedBox.shrink();
    }
  }

  Widget _shareImage1() {
    // 防止日期为空时报错(默认当前日期)
    _model!.publishTime ??= DateTime.now();
    var monthStr = formatDate(_model?.publishTime, [M]);
    return RepaintBoundary(
      key: globalKey1,
      child: loadNetworkAssetImage(
        _model!.imageUrl,
        key: Key("swiper_key_0"),
        fit: BoxFit.cover,
        width: double.infinity,
        child: Stack(
          children: <Widget>[
            Padding(
              padding: EdgeInsets.all(Dimens.gapDp15),
              child: Row(
                children: <Widget>[
                  ClipRRect(
                    borderRadius: BorderRadius.circular(3.0),
                    child: loadImage(
                      "icon_app",
                      width: 20.0,
                      height: 20.0,
                    ),
                  ),
                  Gaps.hGap5,
                  Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    mainAxisSize: MainAxisSize.min,
                    children: <Widget>[
                      Text(
                        "米茫",
                        textScaler: TextScaler.linear(_textScaleFactor),
                        style: Theme.of(context).textTheme.labelSmall!.copyWith(
                              color: Colors.white,
                            ),
                      ),
                      Text(
                        "谁的青春不迷茫",
                        textScaler: TextScaler.linear(_textScaleFactor),
                        style: Theme.of(context).textTheme.labelSmall!.copyWith(
                              color: Colors.white,
                            ),
                      ),
                    ],
                  ),
                ],
              ),
            ),
            Positioned(
              left: Dimens.gapDp12,
              right: Dimens.gapDp12,
              bottom: Dimens.gapDp35,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                mainAxisSize: MainAxisSize.min,
                children: <Widget>[
                  Text(
                    "${_model?.publishTime?.day ?? '--'}",
                    textScaler: TextScaler.linear(_textScaleFactor),
                    style: Theme.of(context).textTheme.displayLarge!.copyWith(
                          height: 1.0,
                          color: Colors.white,
                        ),
                  ),
                  Text(
                    "$monthStr ${_model?.publishTime?.year ?? '--'}",
                    textScaler: TextScaler.linear(_textScaleFactor),
                    style: Theme.of(context).textTheme.labelMedium!.copyWith(
                          color: Colors.white,
                        ),
                  ),
                  Gaps.vGap12,
                  Text(
                    _model?.content ?? "",
                    textScaler: TextScaler.linear(_textScaleFactor),
                    style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                          height: 1.2,
                          color: Colors.white,
                        ),
                  ),
                  Gaps.vGap10,
                  Text(
                    "——",
                    textScaler: TextScaler.linear(_textScaleFactor),
                    style: Theme.of(context).textTheme.labelMedium!.copyWith(
                          color: Colors.white,
                        ),
                  ),
                  Gaps.vGap12,
                  Text(
                    "${_model?.source ?? ''}",
                    textScaler: TextScaler.linear(_textScaleFactor),
                    style: Theme.of(context).textTheme.labelMedium!.copyWith(
                          color: Colors.white,
                        ),
                  ),
                ],
              ),
            ),
            Positioned(
              bottom: Dimens.gapDp10,
              right: Dimens.gapDp10,
              child: Row(
                children: <Widget>[
                  SizedBox(
                    width: Dimens.gapDp10,
                    child: Text(
                      "扫码下载",
                      textScaler: TextScaler.linear(_textScaleFactor),
                      maxLines: 4,
                      style: TextStyle(
                        fontSize: 8,
                        height: 1.5,
                        color: Colors.white,
                      ),
                    ),
                  ),
                  Gaps.hGap2,
                  Container(
                    color: Colors.white,
                    width: 40.0,
                    height: 40.0,
                    child: QrImageView(
                      data: Configs.WEB_QRIMAGE,
                      version: QrVersions.auto,
                      size: 40.0,
                      padding: EdgeInsets.all(2),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
    );
  }

  Widget _shareImage2() {
    // 防止日期为空时报错(默认当前日期)
    _model!.publishTime ??= DateTime.now();
    var monthStr = formatDate(_model?.publishTime, [M]);
    return RepaintBoundary(
      key: globalKey2,
      child: Container(
        padding: EdgeInsets.all(Dimens.gapDp10),
        color: Colors.white,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: <Widget>[
            AspectRatio(
              aspectRatio: 1.0,
              child: loadNetworkAssetImage(
                _model!.imageUrl,
                key: Key("swiper_key_0"),
                fit: BoxFit.cover,
                width: double.infinity,
                child: Column(
                  children: <Widget>[
                    Gaps.vGap10,
                    Row(
                      children: <Widget>[
                        Visibility(
                          visible: false,
                          child: Text("标签"),
                        ),
                        Spacer(),
                        Column(
                          children: <Widget>[
                            Text(
                              "${_model?.publishTime?.day ?? '--'}",
                              textScaler: TextScaler.linear(_textScaleFactor),
                              style: Theme.of(context)
                                  .textTheme
                                  .displayLarge!
                                  .copyWith(
                                    height: 1.0,
                                    color: Colors.white,
                                  ),
                            ),
                            Text(
                              "$monthStr",
                              textScaler: TextScaler.linear(_textScaleFactor),
                              style: Theme.of(context)
                                  .textTheme
                                  .labelMedium!
                                  .copyWith(color: Colors.white),
                            ),
                          ],
                        ),
                        Gaps.hGap10,
                      ],
                    ),
                    Spacer(),
                    Text(
                      "米茫日贴",
                      textScaler: TextScaler.linear(_textScaleFactor),
                      style: Theme.of(context).textTheme.titleMedium!.copyWith(
                          color: Colors.white, letterSpacing: Dimens.gapDp35),
                    ),
                    Gaps.vGap10,
                  ],
                ),
              ),
            ),
            Gaps.vGap16,
            Expanded(
              child: Text(
                _model?.content ?? "",
                maxLines: ScreenUtil.bottomBarHeight == 0 ? 5 : 6,
                overflow: TextOverflow.ellipsis,
                textScaler: TextScaler.linear(_textScaleFactor),
                style: Theme.of(context).textTheme.bodyMedium!.copyWith(
                      height: 1.3,
                      letterSpacing: 1.3,
                      color: Colors.black,
                    ),
              ),
            ),
            Gaps.vGap10,
            Text(
              "${_model?.source ?? ''}",
              textScaler: TextScaler.linear(_textScaleFactor),
              style: Theme.of(context).textTheme.labelMedium!.copyWith(
                    height: 1.0,
                    color: Colors.black54,
                  ),
            ),
            Gaps.vGap8,
            Divider(
              height: 1.0,
              thickness: 1.0,
              indent: 0.0,
              color: Colors.black12,
            ),
            Gaps.vGap8,
            Row(
              children: <Widget>[
                ClipRRect(
                  borderRadius: BorderRadius.circular(3.0),
                  child: loadImage(
                    "icon_app",
                    width: 20.0,
                    height: 20.0,
                  ),
                ),
                Gaps.hGap5,
                Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    Text(
                      "米茫",
                      textScaler: TextScaler.linear(_textScaleFactor),
                      style: Theme.of(context).textTheme.labelMedium!.copyWith(
                            height: 1.0,
                            color: Colors.black,
                          ),
                    ),
                    Text(
                      "谁的青春不迷茫",
                      textScaler: TextScaler.linear(_textScaleFactor),
                      style: Theme.of(context).textTheme.titleSmall!.copyWith(
                            height: 1.0,
                            color: Colors.black54,
                          ),
                    ),
                  ],
                ),
                Spacer(),
                Container(
                  color: Colors.white,
                  width: 40.0,
                  height: 40.0,
                  child: QrImageView(
                    data: Configs.WEB_QRIMAGE,
                    version: QrVersions.auto,
                    size: 40.0,
                    padding: EdgeInsets.all(2.0),
                  ),
                ),
              ],
            ),
          ],
        ),
      ),
    );
  }

  Widget _shareImage3() {
    return RepaintBoundary(
      key: globalKey3,
      child: loadNetworkAssetImage(
        _model!.imageUrl,
        key: Key("swiper_key_0"),
        fit: BoxFit.cover,
        child: Padding(
          padding: EdgeInsets.all(Dimens.gapDp18),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              Align(
                alignment: Alignment.centerRight,
                child: Text(
                  "#米茫日贴",
                  textScaler: TextScaler.linear(_textScaleFactor),
                  style: Theme.of(context).textTheme.labelMedium!.copyWith(
                        color: Colors.white,
                      ),
                ),
              ),
              Spacer(),
              Text(
                _model?.content ?? "",
                textScaler: TextScaler.linear(_textScaleFactor),
                style: Theme.of(context).textTheme.titleMedium!.copyWith(
                      height: 1.2,
                      color: Colors.white,
                    ),
              ),
              Gaps.vGap15,
              Align(
                alignment: Alignment.centerRight,
                child: Text(
                  "—— ${_model?.source ?? ''}",
                  textScaler: TextScaler.linear(_textScaleFactor),
                  style: Theme.of(context).textTheme.labelMedium!.copyWith(
                        color: Colors.white,
                      ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  // 底部分享布局
  Widget _buildBottom() {
    return Positioned(
      left: Dimens.gapDp10,
      bottom: animation.value,
      right: Dimens.gapDp10,
      child: Material(
        borderRadius: BorderRadius.all(Radius.circular(Dimens.gapDp30)),
        child: Container(
          height: _bottomShareHeight,
          margin: EdgeInsets.all(Dimens.gapDp6),
          padding: EdgeInsets.symmetric(vertical: Dimens.gapDp8),
          alignment: Alignment.center,
          child: Column(
            children: <Widget>[
              Text(
                i18n(context).share,
                textScaler: TextScaler.linear(1.0),
                style: Theme.of(context).textTheme.titleLarge,
              ),
              Gaps.vGap15,
              Expanded(
                child: ListView(
                  scrollDirection: Axis.horizontal,
                  children: <Widget>[
                    _widgetItem(
                      title: i18n(context).download,
                      iconData: Iconfont.xiazai,
                      iconColor: Color(0xFF777777),
                      fillColor: Color(0xFFF5F4F5),
                      onPressed: () {
                        _downLoad();
                      },
                    ),
                    _widgetItem(
                      title: i18n(context).wallpaper,
                      iconData: Iconfont.icongenghuanbizhi,
                      iconColor: Color(0xFFC6A253),
                      fillColor: Color(0xFFF5F4F5),
                      onPressed: _saveWallpaper,
                    ),
                    _widgetItem(
                      title: i18n(context).wxChatSession,
                      iconData: Iconfont.weixinhaoyou,
                      iconColor: Colors.white,
                      fillColor: Color(0xFF70CB5B),
                      onPressed: () {
                        _shareWeChat(WeChatScene.session);
                      },
                    ),
                    _widgetItem(
                      title: i18n(context).wxChatTimeline,
                      iconData: Iconfont.pengyouquan1,
                      iconColor: Colors.white,
                      fillColor: Color(0xFF70CB5B),
                      onPressed: () {
                        _shareWeChat(WeChatScene.timeline);
                      },
                    ),
                    // _widgetItem(
                    //   title: i18n(context).sina,
                    //   iconData: Iconfont.xinlang1,
                    //   iconColor: Colors.white,
                    //   fillColor: Color(0xFFDC6C55),
                    //   onPressed: () {},
                    // ),
                    // _widgetItem(
                    //   title: i18n(context).qq,
                    //   iconData: Iconfont.qq,
                    //   iconColor: Colors.white,
                    //   fillColor: Color(0xFF6CB4F3),
                    //   onPressed: () {},
                    // ),
                    // _widgetItem(
                    //   title: i18n(context).browser,
                    //   iconData: Iconfont.liulanqi,
                    //   iconColor: Colors.white,
                    //   fillColor: Color(0xFF5099E8),
                    //   onPressed: _openBrowser,
                    // ),
                    _widgetItem(
                      title: i18n(context).more,
                      iconData: Iconfont.gengduo1,
                      iconColor: Color(0xFF777777),
                      fillColor: Color(0xFFF5F4F5),
                      onPressed: _systemShare,
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  /// 分享按钮Item
  _widgetItem(
      {required String title,
      IconData? iconData,
      Color? fillColor,
      Color? iconColor,
      Function? onPressed}) {
    return Container(
      width: Dimens.widthDp(115.0),
      margin: EdgeInsets.symmetric(horizontal: Dimens.gapDp10),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Expanded(
            child: RawMaterialButton(
              onPressed: onPressed as void Function()?,
              child: Icon(iconData, color: iconColor),
              shape: CircleBorder(),
              elevation: 0.0,
              highlightElevation: 0.0,
              fillColor: fillColor,
            ),
          ),
          Gaps.vGap8,
          Text(
            title,
            textScaler: TextScaler.linear(1.0),
            maxLines: 1,
            style: Theme.of(context).textTheme.titleSmall,
          ),
        ],
      ),
    );
  }

  void _downLoad() async {
    if (await Permission.storage.request().isGranted) {
      ui.Image? image = await _selectImageOfIndex();
      if (image != null) {
        saveImageGallerSaver(image).then((val) {
          Toast.showSuccess("保存至相册");
        });
      } else {
        Toast.showError("生成图片异常");
      }
    }
  }

  /// 根据索引获取当前图片文件
  Future<ui.Image?> _selectImageOfIndex() async {
    ui.Image? image;
    try {
      switch (selectIndex) {
        case 0:
          image = await _capturePng(globalKey1);
          break;
        case 1:
          image = await _capturePng(globalKey2);
          break;
        case 2:
          image = await _capturePng(globalKey3);
          break;
        default:
      }
    } catch (e) {
      print(e.toString());
    }
    return Future.value(image);
  }

  /// 保存图片到相册
  Future<dynamic> saveImageGallerSaver(
    ui.Image image, {
    format = ui.ImageByteFormat.png,
  }) async {
    ByteData? byteData = await (image.toByteData(format: format));
    if (byteData != null) {
      // Uint8List pngBytes = byteData.buffer.asUint8List();
      // return ImageGallerySaver.saveImage(
      //   pngBytes,
      //   quality: 100,
      // );
    } else {
      Toast.showError("保存图片异常");
    }
    return Future.value();
  }

  _saveWallpaper() async {
    var imageUrl = _model!.imageUrl;
    if (!_model!.imageUrl!.startsWith(RegExp(r"https?:"))) {
      imageUrl = "${Configs.IMAGE_BASE_URL}/$_model.imageUrl";
      List<String> s = _model!.imageUrl!.split(":/");
      imageUrl = s[0] + ':/' + s[1].replaceAll("//", "/");
    }
    if (!imageUrl!.contains("?")) {
      var pixelRatio = ScreenUtil.pixelRatio;
      var width = ScreenUtil.screenWidth.toInt();
      var height = ScreenUtil.screenHeight.toInt();
      print("w: $width ; H: $height; pixelRatio: $pixelRatio");
      imageUrl += "?imageView2/1/w/$width/h/$height/";
    }

    var response = await Dio().get<Uint8List>(
      imageUrl,
      options: Options(responseType: ResponseType.bytes),
    );
    // 打印字节数
    print(response.data!.length);
    // final result = await ImageGallerySaver.saveImage(
    //   response.data!,
    //   quality: 100,
    // );
    // if (result is Map && result['isSuccess'] == true) {
    //   Toast.showSuccess("保存至相册");
    // } else {
    //   Toast.showError("保存失败");
    // }
  }

  /// 生成图片
  Future<ui.Image> _capturePng(GlobalKey globalKey) {
    RenderRepaintBoundary boundary =
        globalKey.currentContext!.findRenderObject() as RenderRepaintBoundary;
    double dpr =
        View.of(globalKey.currentContext!).devicePixelRatio; // 使用 View.of 获取像素比
    return boundary.toImage(pixelRatio: dpr);
  }

  /// 微信分享
  /// scene 分享类别(好友,朋友圈...)
  void _shareWeChat(WeChatScene scene) async {
    // 判断是否安装微信
    if (await Fluwx().isWeChatInstalled) {
      _selectImageOfIndex().then((image) {
        if (image != null) {
          _wixinShare(scene, image);
        }
      });
    } else {
      Toast.showWarn("没有安装微信");
    }
  }

  _wixinShare(WeChatScene scene, ui.Image? image) async {
    if (image == null) {
      Toast.showWarn("无效的分享内容");
      return;
    }
    try {
      ByteData? byteData =
          await (image.toByteData(format: ui.ImageByteFormat.png));
      if (byteData == null) {
        Toast.showWarn("分享内容异常");
        return;
      }
      Uint8List pngBytes = byteData.buffer.asUint8List();
      var source = WeChatImageToShare(uint8List: pngBytes);
      WeChatShareModel shareModel = WeChatShareImageModel(
        source,
        title: "米茫",
        scene: scene,
        description: "工作之余,可以看一些清新美图,让忙碌的生活得到一些放松,补充一些正能量。",
        messageExt: "yymimang",
        mediaTagName: "image",
      );
      Fluwx().share(shareModel);
    } catch (e) {
      print(e.toString());
      Toast.showError("分享异常");
    }
  }

  // /// 浏览器打开
  // void _openBrowser() {
  //   var _shareUrl =
  //       "${Configs.IMAGE_BASE_URL}${_model?.pictureUrl ?? ''}?imageView2/1/w/750/h/1334/format/jpg/q/70|imageslim";
  //   if (_shareUrl.startsWith(RegExp(r'http://|https://|www.'))) {
  //     Toast.showMsg("无效的分享内容");
  //     return;
  //   }
  //   launch(_shareUrl);
  // }

  /// 系统分享,目前只支持文本or链接
  Future<void> _systemShare() async {
    if (_model?.imageUrl == null) {
      Toast.showWarn("无效的分享内容");
      return;
    }
    final RenderBox box = context.findRenderObject() as RenderBox;
    String path = await captureImagePath();
    Share.shareXFiles([XFile(path)],
        text: _model?.content,
        sharePositionOrigin: box.localToGlobal(Offset.zero) & box.size);
  }

  /// 截屏图片生成图片流ByteData
  Future<String> captureImagePath() async {
    var filePath = "";
    ui.Image? image = await _selectImageOfIndex();
    if (image != null) {
      // 将image转化成byte
      ByteData? byteData = await image.toByteData(format: ImageByteFormat.png);
      Uint8List pngBytes = byteData!.buffer.asUint8List();
      // 获取手机存储（getTemporaryDirectory临时存储路径）
      Directory applicationDir = await getTemporaryDirectory();
      // getApplicationDocumentsDirectory();
      // 判断路径是否存在
      bool isDirExist = await Directory(applicationDir.path).exists();
      if (!isDirExist) Directory(applicationDir.path).create();
      // 直接保存，返回的就是保存后的文件
      File saveFile = await File(
        "${applicationDir.path}${DateTime.now().toIso8601String()}.jpg",
      ).writeAsBytes(pngBytes);
      filePath = saveFile.path;
    }
    return filePath;
  }

  @override
  void dispose() {
    controller.dispose();
    super.dispose();
  }
}
